<?php
namespace control;
/*
*公客池设置类
*/

class clientPoolSettingClass extends adIndexClass
{
    private const page = 'clientPoolSetting';
    private const table = 'pool';
    private const title = '客户池设置';

    public static function getDepartmentAll($data = [], $id = ''): string
    {
        // 条件
        $data['where'] = $data['where'] ?? "";
        // 点击事件
        $data['click'] = $data['click'] ?? "replaceDetail(this,'" . self::page . "')";
        // 结果
        $result = find(['table' => 'pool', 'where' => $data['where'] . " and type = '公客池' and coid = '".self::$coid."' order by time asc"]);
        $style = '';
        $temp = "<ul pid='0' {$style} {$data['where']}>";
        $textcontent_ico = "<span class='textcontent_ico'></span>";
        if (is_array($result['array'])) {
            foreach ($result['array'] as $value) {
                $active = $id == $value['id'] ? 'active' : '';
                $temp .= "<li data-id='{$value['id']}' onclick=\"{$data['click']}\" class='$active'><span class='textcontent'>{$textcontent_ico}{$value['name']}</span></li>";
            }
        }
        $temp .= '</ul>';
        return $temp;
    }

    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson(): string
    {
        $option = [];
        $json['html'] = self::getDepartmentAll($option);
        return json_encode($json, 320);
    }


    /*列表页-查询条件*/
    public function home()
    {
        $id = $this->get('id');
        $option['click'] = "replaceDetail(this,'" . self::page . "')";
        $all = $this->getDepartmentAll($option, $id);
        $noneWord = L('clientPoolSetting.home.none');
        $rightHtml = <<<EOT
            <div class="container-no">
                <img class="container-no-img" src="{$this->root}img/control/department-no.svg">
                <p class="center gray">{$noneWord}</p>
            </div>
EOT;
        $html = componentClass::leftNav([
            'title'=>L('clientPoolSetting.home.search'),
            'click'=>$option['click'],
            'button'=>"<img class='tool-img' title='".L('clientPoolSetting.home.newClientPool')."' onclick=\"replaceRightDetail('".suiji()."')\" src='".root."img/control/list_add.svg'>",
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
        $html .= <<<EOT
<script>
var id = '$id'
if(id){
    replaceRightDetail(id)
}
//分类下拉菜单页面
$(".dots").click(function(event) {
    $(".stateBlock").hide();
    let obj = $(this).find(".stateBlock");
      let state = obj.css('display');
    if (state == 'block') {
        obj.hide();
    } else {
        obj.show();
    }
　　　event.stopPropagation()
})
 //点击非下拉区域隐藏
$(document).bind('click', function (e) {
    let target = $(".stateBlock");
    if(!target.is(e.target) && target.has(e.target).length ===0){
      clearDiv();
    }
});
 function clearDiv(){
      $(".stateBlock").hide();
 }
 function replaceRightDetail(id){
            let api = root + 'control/adIndex.html?cla={$this->get('cla')}&fun=edit'
            $.post(api, {id: id}, function (data) {
                $('#container-detail').html(data.html)
            }, "json");
        }
 function cancelPage(id){
    let obj =  $("[data-id='"+id+"']");
    replaceDetail(obj,'clientPoolSetting');
}
 $(function (){
     cancelPage('defaultClientPool')
 })
</script>
EOT;

        //返回
        return $this->homeFun($html);
    }


    /*编辑部门基本资料-弹出层*/
    public function edit()
    {
        //数据查询
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        //按钮
        $button = [];
        if ($this->power(self::page, "edit")) {
            $button[] = [
                "name" => L('clientPoolSetting.edit.save'),
                "type" => "点击事件",
                "fun" => "subForm('" . self::page . "EditForm','".root."control/adIndex.html?cla=". self::page ."&fun=editEdit')",
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => L('clientPoolSetting.edit.cancel'),
                "type" => "点击事件",
                "fun" => "cancelPage('{$info['id']}')",
            ];
        }
        $body = "<div class='tab-button'>".$this->tableShowButton($button)."</div>";
        $body           .= $this->edit4([
            [
                [
                    must . L('clientPoolSetting.edit.name') => text(array('name' => 'name', 'value' => $info['name'])),
                ],
                [
                    L('clientPoolSetting.edit.list') => text(array('name' => 'list', 'value' => $info['list'])),
                ],
                [
                    must . L('clientPoolSetting.edit.manager') => selectMultiple(array('name' => 'manager', 'value' => $info['manager'], 'title' => L('clientPoolSetting.edit.manager'), 'table' => 'staff', 'sqlId' => "stid", 'sqlField' => 'name')),
                ],
                [
                    '&nbsp' => checkbox(array('name' => 'isCooper', 'value' => ['1' => L('clientPoolSetting.edit.isCooper')], 'checked' => [$info['isCooper']]))
                ],
                [
                    must . L('clientPoolSetting.edit.isSee') => radio(array('name' => 'isSee', 'value' => ['1' => L('clientPoolSetting.edit.member_visible'), '0' => L('clientPoolSetting.edit.member_invisible')], 'checked' => $info['isSee'])),
                ],
                [
                    must . L('clientPoolSetting.edit.collaborator') => selectMultiple(array('name' => 'collaborator[]', 'multiple' => true, 'value' => $info['collaborator'], 'title' => L('clientPoolSetting.edit.collaborator'), 'table' => 'staff', 'sqlId' => "stid", 'sqlField' => 'name')),
                ],
//                [
//                    must . "领取额度" => "单次最多可领&nbsp;" . text(array('name' => 'maxNum', 'value' => $info['maxNum'])) . "个客户",
//                ],
//                [
//                    must . "领取频率" => "连续&nbsp;" . text(array('name' => 'frequency', 'value' => $info['frequency'])) . "天内不能领取同一个客户",
//                ],
                [
                    must . L('clientPoolSetting.edit.limitMinute') => radio(array('name' => 'limitMinute', 'value' => ['-1' => L('clientPoolSetting.edit.unlimited'), '1' => str_replace(['{{limitMinute}}'], [text(['name' => 'minute', 'value' => $info['limitMinute'] != -1 ? $info['limitMinute'] : ''])], L('clientPoolSetting.edit.obsolete_automatic_recycling'))], 'checked' => $info['limitMinute'] != -1 ? '1' : '-1')),
                ],
                [
                    must . L('clientPoolSetting.edit.automatic_recycling') => radio(array('name' => 'recycling', 'value' => ['-1' => L('clientPoolSetting.edit.unlimited'), '1' => str_replace(['{{recycling}}'], [text(['name' => 'recyclingDay', 'value' => $info['recycling'] != -1 ? $info['recycling'] : ''])], L('clientPoolSetting.edit.noFollowClue'))], 'checked' => $info['recycling'] != -1 ? '1' : '-1')),
                ],
                [
                    L('clientPoolSetting.edit.recycle_reminder') => str_replace(['{{remindDay}}'], [text(array('name' => 'remindDay', 'value' => $info['remindDay']))], L('clientPoolSetting.edit.remindDay')),
                ],
            ]
        ]);
        //生成表单
        $json['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name'=>'id','value'=>$this->post('id')])
        ]);
        //返回
        return json_encode($json, 320);
    }

    /*部门基本信息-异步处理*/
    public function editEdit()
    {
        $id = $this->post('id')?:self::getId();
        //赋值
        $field = [
            "name" => $this->post('name'),
            'list' => $this->post('list'),
            'isSee' => $this->post('isSee'),
            "isCooper" => is_array($this->post('isCooper'))?$this->post('isCooper')[0]:0,
            "manager" => $this->post('manager'),
//            'maxNum' => $this->post('maxNum'),
//            "frequency" => $this->post('frequency'),
            "remindDay" => $this->post('remindDay'),
            'limitMinute'=>$this->post('minute'),
            'recycling'=>$this->post('recyclingDay'),
            'collaborator' => $this->post('collaborator') && is_array($this->post('collaborator')) ? implode(',', array_unique($this->post('collaborator'))) : '',
        ];
        if ($this->post('limitMinute')==-1){
            $field['limitMinute'] = -1;
        }
        if ($this->post('recycling')==-1){
            $field['recycling'] = -1;
        }
        $annotation = [
            'name' => L('clientPoolSetting.editEdit.name'),
            'manager' => L('clientPoolSetting.editEdit.manager'),
            "collaborator" => L('clientPoolSetting.editEdit.collaborator'),
//            'frequency' => '领取频率',
            'limitMinute' => L('clientPoolSetting.editEdit.limitMinute'),
            'recycling' => L('clientPoolSetting.editEdit.recycling'),
        ];
        $rules = [
            'name' => 'required',
            'manager' => 'required',
            "collaborator" => 'required',
//            "maxNum" => 'required',
//            'frequency' => 'required',
            'limitMinute' => 'required',
            'recycling' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('clientPoolSetting.editEdit.power');
        } elseif (empty($field['limitMinute'])) {
            $json['warn'] = L('clientPoolSetting.editEdit.limitMinuteEmpty');
        } elseif (empty($field['recycling'])) {
            $json['warn'] = L('clientPoolSetting.editEdit.recyclingEmpty');
        } elseif (empty($id)) {
            $json['warn'] = L('clientPoolSetting.editEdit.IDEmpty');
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id,'type'=>'公客池','coid'=>self::$coid, 'stid' => self::$stid, "time" => $this->time]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = str_replace(['{{staffName}}','{{type}}'], [$this->control['name'],$type], L('clientPoolSetting.editEdit.log')) . $field['name'];
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&id=" . $id;
            $json['warn'] = 2;
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    public function detail()
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        if (!$this->power(self::page, "see")) {
            $json['warn'] = L('clientPoolSetting.detail.power');
        } elseif (empty($this->post('id'))) {
            $json['warn'] = L('clientPoolSetting.detail.IDEmpty');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('clientPoolSetting.detail.empty');
        } else {
            $data = [
                "id" => $info['id'],
                "title" => $info['name'],
            ];
            //按钮
            $button = [];
            if ($this->power(self::page, "edit")) {
                $button[] = [
                    "name" => L('clientPoolSetting.detail.edit'),
                    "type" => "点击事件",
                    "fun" => "replaceRightDetail('{$info['id']}')",
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "del") && $info['id'] !='defaultClientPool') {
                $button[] = [
                    "name" => L('clientPoolSetting.detail.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            $body = "<div class='tab-button'>".$this->tableShowButton($button)."</div>";
            $body           .= $this->edit4([
                [
                    [
                        must . L('clientPoolSetting.edit.name') => $info['name'],
                    ],
                    [
                        L('clientPoolSetting.edit.list') => $info['list'],
                    ],
                    [
                        must . L('clientPoolSetting.edit.manager') => self::findStaff($info['manager']),
                    ],
                    [
                        '&nbsp' => checkbox(array('name' => 'isCooper', 'value' => ['1' => L('clientPoolSetting.edit.isCooper')], 'checked' => [$info['isCooper']]))
                    ],
                    [
                        must . L('clientPoolSetting.edit.isSee') => radio(array('name' => 'isSee', 'value' => ['1' => L('clientPoolSetting.edit.member_visible'), '0' => L('clientPoolSetting.edit.member_invisible')], 'checked' => $info['isSee'])),
                    ],
                    [
                        must . L('clientPoolSetting.edit.collaborator') => clueClass::showMember($info['collaborator']),
                    ],
//                    [
//                        must . "领取额度" => $info['maxNum'] == '-1' ? '不限额度' : "单次最多可领【" . $info['maxNum'] . "】个客户",
//                    ],
//                    [
//                        must . "领取频率" => $info['frequency'] == '-1' ? '不限频率' : "连续【" . $info['frequency'] . "】天内不能领取同一个客户",
//                    ],
                    [
                        must . L('clientPoolSetting.edit.limitMinute') => $info['limitMinute'] == '-1' ? L('clientPoolSetting.edit.unlimited') : str_replace(['{{limitMinute}}'], [$info['limitMinute']], L('clientPoolSetting.edit.obsolete_automatic_recycling')),
                    ],
                    [
                        must . L('clientPoolSetting.edit.automatic_recycling') => $info['recycling'] == '-1' ? L('clientPoolSetting.edit.no_automatic_recycling') : str_replace(['{{recycling}}'], [$info['recycling']], L('clientPoolSetting.edit.noFollowClue')),
                    ],
                    [
                        L('clientPoolSetting.edit.recycle_reminder') => $info['remindDay'] == 0 ? L('clientPoolSetting.edit.no_prompt') : str_replace(['{{remindDay}}'], [$info['remindDay']], L('clientPoolSetting.edit.remindDay')),
                    ],
                ]
            ]);
            //生成表单
            $data['html'] = $this->pageEdit([
                "html" => $body,
            ]);
            //生成页面
            $json['warn'] = 2;
            $json['html'] = $data['html'];
        }
        //返回
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('clientPoolSetting.operate.del');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('clientPoolSetting.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }
    /*行政人事-部门管理-删除部门*/
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('clientPoolSetting.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('clientPoolSetting.delete.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['manager'] != self::$stid) {
                    //返回
                    $warn = L('clientPoolSetting.delete.fail');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = L('clientPoolSetting.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], L('clientPoolSetting.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('clientPoolSetting.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('clientPoolSetting.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
